#region license
/*
 * Copyright (C) 2007 CchenSoft.com
 * 
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License 2.1 or later, as
 * published by the Free Software Foundation. See the included License.txt
 * or http://www.gnu.org/copyleft/lesser.html for details.
 * 
 * Author: Billy Zhang
 */
#endregion

using System;
using System.Collections;
using System.Collections.Generic;

using CchenSoft.Workflow.Spi;
using CchenSoft.Common.Utils;

namespace CchenSoft.Workflow.Util
{
    /**
     * Simple utility condition that returns true if the current step's status is
     * the same as the required argument "status". Looks at ALL current steps unless
     * a stepId is given in the optional argument "stepId".
     */
    public class StatusCondition : ICondition
    {
        //~ Methods ////////////////////////////////////////////////////////////////

        public bool PassesCondition(IDictionary transientVars, IDictionary args)
        {
            string status = ConvertUtil.GetSafeString((string)args["status"]);
            int stepId = 0;
            object stepIdVal = args["stepId"];

            if (stepIdVal != null)
            {
                try
                {
                    stepId = Convert.ToInt32(stepIdVal.ToString());
                }
                catch (Exception ex)
                {
                }
            }

            IWorkflowEntry entry = (IWorkflowEntry)transientVars["entry"];
            IWorkflowStore store = (IWorkflowStore)transientVars["store"];
            IList<IStep> currentSteps = store.FindCurrentSteps(entry.Id);

            if (stepId == 0)
            {
                foreach (IStep step in currentSteps)
                {
                    if (status.Equals(step.Status))
                    {
                        return true;
                    }
                }
            }
            else
            {
                foreach (IStep step in currentSteps)
                {
                    if (stepId == step.StepId)
                    {
                        if (status.Equals(step.Status))
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }
    }
}
